package org.adream.dreamnt;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

import org.jose4j.json.JsonUtil;
import org.jose4j.lang.JoseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import com.sensorsdata.analytics.javasdk.SensorsAnalytics;

/**
 * 工具类
 * @author sl
 *
 */
public class Util {
	
	private final static Logger logger = LoggerFactory.getLogger(Util.class);
	
	private static SensorsAnalytics sa = null;
	
	static {
		try {
			sa = new SensorsAnalytics(new SensorsAnalytics.ConcurrentLoggingConsumer(GlobalContext.SENSOR_DATA_LOG_FILE));
		} catch (Exception e) {
			logger.warn("获取神测数据工具初始化错误:(");
		}
	}

	public static void saProfileSet(String uid, boolean b, String string, String unionid) {
		if(sa==null)
    		return;
    	try {
    		sa.profileSet(uid, b, string, unionid);
			sa.flush();
		} catch (Exception e) {
			logger.warn(e.getMessage());
		}
	}
    public static void saTrack(String distinctId, boolean isLoginId, String eventName, Map<String, Object> properties) {
    	if(sa==null)
    		return;
    	try {
    		sa.track(distinctId, isLoginId, eventName, properties);
			sa.flush();
		} catch (Exception e) {
			logger.warn(e.getMessage());
		}
    }
	public static void saTrackSignUp(String uid, String anonymousId) {
		try {
    		sa.trackSignUp(uid,anonymousId);
			sa.flush();
		} catch (Exception e) {
			logger.warn(e.getMessage());
		}
		
	}
	
	/**
	 * 将url地址图片下载到本地
	 * @param urlString		url
	 * @param userPicPath	本地存放图片路径
	 * @return
	 */
	public static String downloadPic(String urlString, String userPicPath) {
		String path = userPicPath.endsWith(File.separator) ? userPicPath : userPicPath + File.separator;
		File file = new File(path);
		if(!file.exists()) {
			file.mkdirs();
		}
		String ext = "jpg";
		String fileName = parseDateToYearMonthDay(new Date()) + "-" + UUIDUtil.createUUID() + "." + ext;
		
		URL url = null;
		DataInputStream dataInputStream = null;
		FileOutputStream fileOutputStream = null;
		try {
			url = new URL(urlString);
			dataInputStream = new DataInputStream(url.openStream());
			fileOutputStream = new FileOutputStream(new File(path + fileName));
			
			byte[] buffer = new byte[1024];
			int length;
			
			while ((length = dataInputStream.read(buffer)) > 0) {
				fileOutputStream.write(buffer, 0, length);
			}
			return fileName;
		} catch (MalformedURLException e) {
			logger.warn("图片下载出错:" + e.getMessage());
			return null;
		} catch (IOException e) {
			logger.warn("图片下载出错:" + e.getMessage());
			return null;
		} finally {
			if(fileOutputStream != null) {
				try {
					fileOutputStream.close();
				} catch (IOException e) {
					logger.warn("图片下载出错:" + e.getMessage());
					return null;
				}
			}
			if(dataInputStream != null) {
				try {
					dataInputStream.close();
				} catch (IOException e) {
					logger.warn("图片下载出错:" + e.getMessage());
					return null;
				}
			}
		}
	}
	
	/**
	 * 时间解析为年月日字符串格式
	 * 月日不足两位前面补0
	 * @param date	日期
	 * @return
	 */
	public static String parseDateToYearMonthDay(Date date) {
		// 获取默认选中的日期的年月日星期的值，并赋值
		Calendar calendar = Calendar.getInstance();// 日历对象
		calendar.setTime(date);// 设置当前日期

		String year = calendar.get(Calendar.YEAR) + "";// 获取年份
		int m = calendar.get(Calendar.MONTH) + 1;// 获取月份
		String month = m < 10 ? "0" + m : m + "";
		int d = calendar.get(Calendar.DATE);// 获取日
		String day = d < 10 ? "0" + d : d + "";
		return year + month + day;
	}
	
    /**url参数转为map
     * 例:a=a1&b=b1&c=c1
     * @param paramStr
     * @return
     */
    public static Map<String, String> urlParamToMap(String paramStr) {
		String[] params = paramStr.split("&");
		Map<String, String> map = new HashMap<String, String>();
		for (int i = 0; i < params.length; i++) {
			String[] param = params[i].split("=");
			if (param.length >= 2) {
				String key = param[0];
				String value = param[1];
				for (int j = 2; j < param.length; j++) {
					value += "=" + param[j];
				}
				map.put(key, value);
			}
		}
		return map;
	}
    
    /**
	 * 验证邮箱地址有效性
	 * @param email	邮箱地址
	 * @return
	 */
	public static boolean verifyEmail(String email) {
		Pattern p = Pattern.compile("^([a-zA-Z0-9_\\.\\-])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$");
		if (StringUtils.isEmpty(email)) {
			return false;
		} else {
			return p.matcher(email).matches();
		}
	}
	
	/**
	 * 验证手机有效性
	 * @param phone	手机号
	 * @return
	 */
	public static boolean verifyPhone(String phone) {
		Pattern p = Pattern.compile("^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$");
		if (StringUtils.isEmpty(phone)) {
			return false;
		} else {
			return p.matcher(phone).matches();
		}
	}
	
	public static void main(String[] args) throws UnsupportedEncodingException, JoseException {
		String url = "%7b%22distinct_id%22%3a%22ADREAM90244%22%2c%22first_id%22%3a%22176dab0696a47-0173431bd0e91d-c791039-2073600-176dab06974127%22%2c%22props%22%3a%7b%22%24latest_traffic_source_type%22%3a%22url%e7%9a%84domain%e8%a7%a3%e6%9e%90%e5%a4%b1%e8%b4%a5%22%2c%22%24latest_search_keyword%22%3a%22url%e7%9a%84domain%e8%a7%a3%e6%9e%90%e5%a4%b1%e8%b4%a5%22%2c%22%24latest_referrer%22%3a%22url%e7%9a%84domain%e8%a7%a3%e6%9e%90%e5%a4%b1%e8%b4%a5%22%7d%2c%22%24device_id%22%3a%22176dab0696a47-0173431bd0e91d-c791039-2073600-176dab06974127%22%7d";
		System.out.println(URLDecoder.decode(url, "UTF-8"));
		Map<String, Object> info = JsonUtil.parseJson(URLDecoder.decode(url, "UTF-8"));
		System.out.println(info.get("distinct_id"));
	}

}